package cn.lkx.servicemsm.service.impl;

import cn.lkx.servicemsm.service.MsmService;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teautil.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {
    @Autowired
    JavaMailSender mailSender; //发送邮件

    /**
     * 将随机4位验证码交给阿里云，发送短信方法
     */
    @Override
    public boolean sendMsm(Map<String, Object> map, String phone) {
        Config config = new Config()
                .setAccessKeyId("LTAI5tENxUmgaoCZnn7C2Crd")
                .setAccessKeySecret("hRoeLZ5VpCYx6veG34opRApwUavHcm");
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        //创建client对象
        Client client = null;
        try {
            client = new Client(config);

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName("阿里云短信测试")  //签名
                    .setTemplateCode("SMS_154950909")  //模板id
                    .setPhoneNumbers(phone)
                    .setTemplateParam(JSONObject.toJSONString(map));
            // 发送出去
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            String isSuccess = sendSmsResponse.getBody().getCode();
            if (Common.equalString(isSuccess,"OK")){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    //QQ邮箱发送验证码
    @Override
    public boolean sendMsmByEmail(String code, String email) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("【MyMooc教育平台】");
        mailMessage.setText("【MyMooc教育平台】 您正在注册验证，验证码"+code+"，切勿将验证码泄露他人，本条验证码有效期5分钟。");
        mailMessage.setFrom("2392998181@qq.com"); //发件人
        mailMessage.setTo(email); //收件人
        try {
            mailSender.send(mailMessage);
            return true;
        }catch (MailException e){
            e.printStackTrace();
            return false;
        }
    }
}
